<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-form-item label="版本" prop="versionId">
        <el-select v-model="formData.versionId" placeholder="请输入版本">
          <el-option
            v-for="dict in projectVersionList"
            :key="dict.id"
            :label="dict.version"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="DevopsCustomerUpgrade" lang="ts">
import * as DevopsCustomerApi from '@/api/infra/devops/customer'
import * as DevopsProjectVersionApi from '@/api/infra/devops/projectVersion'
const projectVersionList = ref()
const dialogTitle = ref('升级')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formData = ref({
  id: undefined,
  version: {
    projectId: undefined
  },
  versionId: undefined
})
const formRules = reactive({
  customerName: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  customerNo: [{ required: true, message: '客户编号不能为空', trigger: 'blur' }],
  versionId: [{ required: true, message: '版本不能为空', trigger: 'change' }],
  serverId: [{ required: true, message: '服务器IP不能为空', trigger: 'change' }],
  databaseName: [{ required: true, message: '数据库名称不能为空', trigger: 'blur' }]
})
/** 打开弹窗 */
const open = async (id) => {
  dialogVisible.value = true

  resetForm()

  formData.value = await DevopsCustomerApi.singleGet(id)
  projectVersionList.value = await DevopsProjectVersionApi.getByProject(
    formData.value.version.projectId
  )
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    version: {
      projectId: undefined
    },
    versionId: undefined
  }
  formRef.value?.resetFields()
  projectVersionList.value = []
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  formLoading.value = true
  try {
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success', formData.value)
  } finally {
    formLoading.value = false
  }
}
</script>
